// 权限控制
import store from '@/store'
import router from './router'
import NProgress from 'nprogress'
import { getUserInfo, getUserDetailById } from '@/api/user'
import 'nprogress/nprogress.css'
// 1. 登录的权限控制
const WHITE_LIST = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 进入页面之前开启进度条
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.state.user.userInfo.username) {
        const res = await getUserInfo()
        const res2 = await getUserDetailById(res.data.userId)
        store.commit('user/setUserInfo', { ...res.data, ...res2.data })
      }
      next()
    }
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 路由后置守卫，路由跳转结束，停止进度条
router.afterEach((to, from) => {
  NProgress.done()
})

// 2. 左侧菜单的权限控制
